package com.mdinic.blogovi.front.page.blogpost;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;

import com.mdinic.blogovi.front.common.AbstractBasePage;
import com.mdinic.blogovi.front.page.HomePage;
import com.mdinic.blogovi.front.page.blogpost.BlogPostPanel.BlogPostPanelType;
import com.mdinic.blogovi.model.Blog;
import com.mdinic.blogovi.model.BlogPost;

/**
 * Class that represents blog post page.
 * 
 * @author mdinic
 */
public class BlogPostListByBlogPage extends AbstractBasePage {

    private static final long serialVersionUID = 1L;

    private final int firstResult = MAX_RESULTS;
    private static final int MAX_RESULTS = 5;

    private int page = 1;

    private final List<BlogPost> list = new ArrayList<BlogPost>();

    /**
     * Constructor.
     */
    public BlogPostListByBlogPage(PageParameters pageParameters) {
        super(false);

        StringValue stringValue = pageParameters.get(URL_PARAM_NAME);

        final Blog blog = Blog.findBlog(stringValue.toOptionalLong());
        if (blog == null) {
            throw new RestartResponseException(HomePage.class);
        }
        add(new ExternalLink("blog_url", blog.getUrl(), blog.getUrl()));

        list.addAll(BlogPost.findBlogPostsByBlog(blog, 0, MAX_RESULTS));

        final BlogPostPanel blogPostPanel = new BlogPostPanel(list, BlogPostPanelType.LIST);
        blogPostPanel.setOutputMarkupId(true);
        add(blogPostPanel);

        final AjaxLink<Void> more = new AjaxLink<Void>("more_link") {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {

                List<BlogPost> toAdd = BlogPost.findBlogPostsByBlog(blog, firstResult * page, MAX_RESULTS);

                if (!toAdd.isEmpty()) {
                    list.addAll(toAdd);
                    target.add(blogPostPanel);
                    page++;
                } else {
                    Component component = getPage().get("more");
                    component.setEnabled(false);
                    target.add(component);
                }
            }
        };
        more.setOutputMarkupId(true);
        add(more);
    }
}
